#ifndef KVDB_SERVER_CONNSERVER_H_
#define KVDB_SERVER_CONNSERVER_H_

#include "vzconn/conn/vzserver.h"
#include "kvdb/server/kvdbsession.h"
#include "kvdb/server/kvdbsqlite.h"
#include "boost/asio/steady_timer.hpp"

namespace kvdb {

class KvdbServer : public boost::noncopyable,
  public boost::enable_shared_from_this < KvdbServer > {
 public:
  typedef boost::shared_ptr<KvdbServer> Ptr;
  KvdbServer(io_service_ptr io_service);
  // default addr 127.0.0.1
  // default port 5299
  bool StartConnServer(const char *listen_addr,
                       unsigned short listen_port,
                       const char *kvdb_path);
  void StopConnServer();
  virtual ~KvdbServer();
 private:
  void OnNewTcpConnect(vzconn::VzServer::Ptr tcp_server,
                       vzconn::VzConnect::Ptr tcp_connect);
  void OnTcpServerError(vzconn::VzServer::Ptr tcp_server,
                        const boost::system::error_code& err);
  void OnSessionError(KvdbSession::Ptr kvdb_session,
                      const boost::system::error_code& err);
  // On
  void WattingNextTransactionAsyncEvent();
  void OnHandleTimeout(const boost::system::error_code& err);
 private:
  static const int ASYNC_TIMEOUT_TIMES = 10;
  io_service_ptr io_service_;
  vzconn::VzServer::Ptr tcp_server_;
  KvdbSqlite::Ptr kvdb_sqlite_;
  std::vector<KvdbSession::Ptr> kvdb_sessions_;
#ifdef WIN32
  boost::scoped_ptr<boost::asio::deadline_timer> timer_;
#else
  boost::scoped_ptr<boost::asio::steady_timer> timer_;
#endif
};
}

#endif // KVDB_SERVER_CONNSERVER_H_